﻿#region The MIT License (MIT)
// The MIT License (MIT)
// Copyright (c) 2010 - 2013 Sovacode LLC
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions
// of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
// BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#endregion

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using Sovacode.RubiksCube.Common.Exceptions;

namespace Sovacode.RubiksCube.Common.Collections
{
    /// <summary>
    /// Advanced collection
    /// </summary>
    /// <typeparam name="T">Type</typeparam>
    [Serializable]
    public class AdvancedObservableCollection<T> : ObservableCollection<T>, INotifyPropertyChanged
    {
        #region Private Fields

        /// <summary>
        /// Occurs when collection changed.
        /// </summary>
        [field: NonSerialized]
        public override event NotifyCollectionChangedEventHandler CollectionChanged;

        /// <summary>
        /// The changed event handler
        /// </summary>
        [field: NonSerialized] 
        private PropertyChangedEventHandler _propertyChangedEventHandler;
        
        private bool _allowNulls = true;

        #endregion

        #region Constructor

        /// <summary>
        /// Initializes a new instance of the <see cref="AdvancedObservableCollection{T}"/> class.
        /// </summary>
        public AdvancedObservableCollection() : base()
        {

        }

        /// <summary>
        /// Initializes a new instance of the <see cref="AdvancedObservableCollection{T}"/> class.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <exception cref="System.NullReferenceException"></exception>
        public AdvancedObservableCollection(IEnumerable<T> source) : base()
        {
            if (source == null)
            {
                throw new NullReferenceException();
            }

            foreach (T obj in source)
            {
                Add(obj);
            }
        }

        #endregion

        #region Events

        /// <summary>
        /// Occurs when property changed.
        /// </summary>
        event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
        {
            add
            {
                _propertyChangedEventHandler =
                    Delegate.Combine(_propertyChangedEventHandler, value) as PropertyChangedEventHandler;
            }
            remove
            {
                _propertyChangedEventHandler =
                    Delegate.Remove(_propertyChangedEventHandler, value) as PropertyChangedEventHandler;
            }
        }

        #endregion

        #region Overrides


        /// <summary>
        /// Raises the <see cref="CollectionChanged" /> event.
        /// </summary>
        /// <param name="e">The <see cref="NotifyCollectionChangedEventArgs"/> instance containing the event data.</param>
        protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            NotifyCollectionChangedEventHandler handler = CollectionChanged;

            if (handler != null)
            {
                handler(this, e);
            }
        }

        /// <summary>
        /// Raises the <see cref="INotifyPropertyChanged.PropertyChanged" /> event.
        /// </summary>
        /// <param name="e">The <see cref="PropertyChangedEventArgs"/> instance containing the event data.</param>
        protected override void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            PropertyChangedEventHandler handler = _propertyChangedEventHandler;

            if (handler != null)
            {
                handler(this, e);
            }
        }


        /// <summary>
        /// Sets the item.
        /// </summary>
        /// <param name="index">The index.</param>
        /// <param name="item">The item.</param>
        /// <exception cref="Sovacode.RubiksCube.Common.Exceptions.NullsNotAllowedException"></exception>
        protected override void SetItem(int index, T item)
        {
            if (!AllowNulls && item == null)
            {
                throw new NullsNotAllowedException();
            }

            base.SetItem(index, item);
        }


        /// <summary>
        /// Inserts the item.
        /// </summary>
        /// <param name="index">The index.</param>
        /// <param name="item">The item.</param>
        /// <exception cref="Sovacode.RubiksCube.Common.Exceptions.NullsNotAllowedException"></exception>
        protected override void InsertItem(int index, T item)
        {
            if (!AllowNulls && item == null)
            {
                throw new NullsNotAllowedException();
            }

            base.InsertItem(index, item);
        }


        #endregion

        #region Helper

        /// <summary>
        /// Add range of objects <see cref="IEnumerable{T}"/>
        /// </summary>
        /// <param name="range">Range <see cref="IEnumerable{T}"/></param>
        public void AddRange(IEnumerable<T> range)
        {
            if (range == null)
            {
                return;
            }

            foreach (T some in range)
            {
                Add(some);
            }
        }

        /// <summary>
        /// Checks if exist item at specific index
        /// </summary>
        /// <param name="index">Index</param>
        /// <returns>True if exist</returns>
        public bool HasIndex(int index)
        {
            int max = Items.Count == 0 ? 0 : Items.Count - 1;

            if (max == 0)
            {
                return false;
            }

            if (index > max)
            {
                return false;
            }

            return index >= 0;
        }

        /// <summary>
        /// Gets or sets a value indicating whether the nulls can be inserted
        /// </summary>
        public bool AllowNulls
        {
            get { return _allowNulls; }
            set
            {
                _allowNulls = value;

                OnPropertyChanged(new PropertyChangedEventArgs("AllowNulls"));
            }
        }

        #endregion
    }
}